<template>
  <el-card>
    <template #header class="clearfix">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="'/home'">首页</el-breadcrumb-item>
        <el-breadcrumb-item>发布文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
    <el-form label-width="80px" :model="form" :rules="rules" ref="form">
      <el-form-item label="标题:" prop="title">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="频道:" prop="channel_id">
        <HmSelect :form="form"></HmSelect>
      </el-form-item>
      <el-form-item label="封面:" prop="cover">
        <el-radio-group v-model="form.cover.type" @change="radioChange">
          <el-radio :label="1">单图</el-radio>
          <el-radio :label="3">三图</el-radio>
          <el-radio :label="0">无图</el-radio>
          <el-radio :label="-1">自动</el-radio>
        </el-radio-group>
        <div v-if="bol">
          <el-upload
            v-if="form.cover.type > 0"
            :action="baseUrl + '/v1_0/upload'"
            :limit="form.cover.type"
            name="image"
            list-type="picture-card"
            :file-list="fileList"
            :before-upload="beforeUp"
            :on-success="upSuc"
            :on-remove="onRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="内容:" prop="content">
        <quillEditor
          @change="editorChange"
          v-model="form.content"
        ></quillEditor>
      </el-form-item>
      <el-form-item>
        <div v-if="$route.query.id">
          <el-button type="primary" @click="editArticle(false)"
            >修改文章</el-button
          >
          <el-button @click="editArticle(true)">存入草稿</el-button>
        </div>
        <div v-else>
          <el-button type="primary" @click="submit(false)">发布文章</el-button>
          <el-button @click="submit(true)">存入草稿</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { articlePost, articlePut, articleGet } from '@/api/index.js'

export default {
  data () {
    return {
      bol: true,
      baseUrl: process.env.VUE_APP_URL,
      form: {
        title: '', //	string	必须		文章标题
        content: '', //	string	必须		文章内容
        cover: {
          //	object	必须
          type: 1, //	string	必须		封面类型 -1:自动，0-无图，1-1张，3-3张
          images: [] //	string	必须		item 类型: string
        },
        channel_id: '' //	number	必须		文章所属频道id
      },
      rules: {
        title: [{ required: true, message: '必填', trigger: 'change' }],
        content: [{ required: true, message: '必填', trigger: 'change' }],
        cover: [
          { required: true, message: '必填', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value.type > 0) {
                // console.log(value.images.length)
                value.images.length === value.type
                  ? callback()
                  : callback(new Error(`请上传${value.type}张图片`))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        channel_id: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  components: {
    quillEditor
  },

  async created () {
    if (this.$route.query.id) {
      const res = await articleGet(this.$route.query.id)
      // console.log(res)
      this.form = res.data
    }
  },
  methods: {
    // 修改图片数量时/清空iamges数组/静默刷新dom
    radioChange () {
      this.form.cover.images = []
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 上传前
    beforeUp (file) {
      // console.log(file)
      const isImg =
        file.type === 'image/jpeg' ||
        file.type === 'image/gif' ||
        file.type === 'image/png'
      const isLimit2m = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('请上传jpeg或者gif')
      }
      if (!isLimit2m) {
        this.$message.error('上传图片不得大于2m')
      }
      return isImg && isLimit2m
    },
    // 上传成功
    upSuc (res) {
      console.log(res)
      this.form.cover.images.push({ url: res.data.url })
      this.$refs.form.validateField(['cover'])
    },
    // 删除前
    onRemove (file) {
      console.log(file)
      const _index = this.form.cover.images.findIndex(item => item === file.url)
      this.form.cover.images.splice(_index, 1)
    },
    // 发布文章
    submit (bol) {
      this.$refs.form.validate(async res => {
        if (res) {
          const res = await articlePost(this.form, bol)
          console.log(res)
          this.$message.success(bol ? '存入草稿成功' : '发布文章成功')
          this.$router.push('/article')
        } else {
          this.$message.error('验证失败')
        }
      })
    },
    // 内容验证
    editorChange () {
      this.$refs.form.validateField(['content'])
    },

    // 修改文章
    async editArticle (bol) {
      const res = await articlePut(this.form, bol, this.$route.query.id)
      console.log(res)
      this.$router.push('/article')
    }
  },
  computed: {
    fileList () {
      return this.form.cover.images.map(item => {
        return { url: item }
      })
    }
  }
}
</script>
<style scoped lang="less">
::v-deep .ql-editor {
  min-height: 120px;
}
</style>
